package com.cn.learn.redis.controller;

import com.cn.learn.redis.util.DateUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName RedisTTLTestController
 * @Description
 * @Author JiJiang
 * @Date 2023/6/26 21:45
 * @Version 1.0
 */
@RestController
@RequestMapping("/test/redis")
public class RedisTTLTestController {


    @Resource
    private RedisTemplate redisTemplate;


    /**
     * 添加 ttl的key
     *
     * @param keyName
     * @param ttl
     * @return
     */
    @PostMapping("/ttl/{keyName}/{ttl}")
    public String ttlAdd(@PathVariable String keyName, @PathVariable Integer ttl) {

        try {

            redisTemplate.opsForValue().set(keyName, DateUtils.getTime());

            redisTemplate.expire(keyName, ttl, TimeUnit.SECONDS);

            return "OK";
        } catch (Exception e) {
            return "Fail";

        }
    }


    @GetMapping("/ttl/{keyName}")
    public Long ttlGet(@PathVariable String keyName) {

        return redisTemplate.opsForValue().getOperations().getExpire(keyName);

    }


}
